#!/bin/bash
jdk_path='/root/JDK'
jdk_install_file='/root/Downloads/jdk-8u202-linux-x64.tar.gz'
JAVA_HOME=''

start_menu() {
    clear
    echo "==============================="
    echo -e "\033[42;30m            INSTALL            \033[0m"
    echo "Number:7210764124              "
    echo "Date:2023年11月15日            "
    echo "==============================="
    echo "                               "
    echo "1. 安装jdk                     "
    echo "2. 卸载jak                     "
    echo "0. 退出                        "
    echo

    read -p "请输入数字: " n

    case $n in
    1)
    # 解压缩
    install;
    # 修改环境变量
    update_env;;
    2) uninstall;;
    0) exit;;
    esac
}

install() {
    # 检查安转目录是否存在
    if [ -d $jdk_path ]
        then
            echo '安装目录存在'
            rm -rf $jdk_path
    fi
    # 创建JDK目录
    mkdir $jdk_path
    # 检查安装文件是否存在
    if [ ! -f $jdk_install_file ]
    then 
        echo "安装文件存在"
        exit
    fi
    # 开始解压缩安装
    tar -xzvf $jdk_install_file -C $jdk_path
    # 判断是否解压成功
    if [ $? -ne 0 ]
    then
        echo "解压失败"
        exit
    fi
    echo 'jdk安装成功'
}

update_env() {
# 找到java的安装目录
    for dir in $jdk_path/*
    do
        if [ -d $dir ]
            then JAVA_HOME=$dir
        fi
    done
    echo "解压完成，jdkdir: $JAVA_HOME"
    # 配置环境变量，修改.bash_profile
    echo "export JAVA_HOME=$JAVA_HOME" >> ~/.bash_profile
    echo 'export PATH=$PATH:$JAVA_HOME/bin' >> ~/.bash_profile
    echo 'export PATH=$PATH:$JAVA_HOME/jre/bin' >> ~/.bash_profile
    
    echo "jdk 安装配置完成"
    source ~/.bash_profile
    java -version
}

uninstall() {
    rm -rf $jdk_path
    sed -i '/JAVA_HOME/d' ~/.bash_profile
    sed -i '/jdk1.8.0/d' ~/.bash_profile
    source ~/.bash_profile
    echo "JDK已成功卸载"
}

install_main() {
start_menu;
}

install_main;
